
import { valid, sendMessageToContentScript, fetchGiftCard, exportExcel } from '../popup/common'
import axios from 'axios'
axios.defaults.timeout=3000;

// background.js文件
chrome.webRequest.onBeforeSendHeaders.addListener(
  function (details) {
    if (details.url.includes('/orchestra/home/graphql')) {
      console.log(details)
      // 检查请求头中是否包含 "ldy"
      let hasLdyHeader = details.requestHeaders.some(header => header.name.toLowerCase() === 'ldy' && header.value);
      console.log('是否是插件发起的请求', hasLdyHeader)
      if (hasLdyHeader) {
        const cookieIndex = details.requestHeaders.findIndex(header => header.name.toLowerCase() === 'cookie');
        // 如果找到 Cookies，清空它
        if (cookieIndex !== -1) {
          console.log('清除cookes')
          details.requestHeaders[cookieIndex].value = '';
        }
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  { urls: ['*://*.walmart.com/*'] },
  ['blocking', 'requestHeaders', 'extraHeaders']
);

chrome.webRequest.onCompleted.addListener(async function (details) {
  if (details.statusCode == 200 && details.url.includes('/orchestra/home/graphql/accountLandingPage/4a906799bb64ea93fe88be278e93fe58284d48fd0d144565ea287400f6cf0942')) {
    console.log('我是懒觉', details)
    
  }
}, { urls: ['*://*.walmart.com/*']  });

chrome.runtime.onMessage.addListener(async (req, sender, sendResponse) => {
  // console.log(req)
  if (req.type === 'msg') {
    alertMsg(req.data)
  }
})

function log(...data) {
  console.log(...data, new Date().toLocaleTimeString())
  sendMessageToContentScript({
    type: 'log',
    data: data
  })
}
function sayMsg(data) {
  sendMessageToContentScript({
    type: 'sayMsg',
    data: data
  })
}
const NOTIFICATION_ID = "alterMsg";
/**
 * 发送通知消息
 * @param {*} param0 
 */
function alertMsg({ title, msg }) {
  chrome.notifications.clear(NOTIFICATION_ID, function () {
    var options = {
      title: title || '提示',
      message: msg || '无',
      type: 'basic',
      iconUrl: 'static/img/icon.png'
    };

    chrome.notifications.create(NOTIFICATION_ID, options, (notificationId) => {
      if (chrome.runtime.lastError) {
        console.error('Error creating notification:', chrome.runtime.lastError);
      } else {
        console.log('Notification created with ID:', notificationId);
      }
    });
  });
}

/**
 * 获取存储
 * @param {*} type 
 * @returns 
 */
function getItem(type) {
  return new Promise(resolve => {
    chrome.storage.local.get(type, (res) => {
      resolve(res[type])
    })
  })
}

/**
 * 设置存储
 * @param {*} data 
 * @returns 
 */
function setItem(data) {
  chrome.storage.local.set(data)
}

window.alertMsg = alertMsg


var proxyUser = '', proxyPass = '', proxyIndex = 0
var failedLogins = 0
var proxyList = null
async function onProxyError(details) {
  log('代理错误', details)
  if (details.error == 'net::ERR_TUNNEL_CONNECTION_FAILED') {
    // 代理不可用，退出
    isRun = false
    setItem({ 'isRun': false })
    emit('isRun', false)
    emit('error', '代理IP不可用net::ERR_TUNNEL_CONNECTION_FAILED')
    return;
  }
  // switchProxy(true)
  let proxyType = await getItem('proxys-type') || '1'
  // 不是动态代理才是异常时候删除。
  if (proxyType != '1' && proxyList && proxyList.length > 0 && proxyList.length > proxyIndex) {
    proxyList.splice(proxyIndex, 1)
  }
}
function makeLogin(details, callbackFn) {
  if (details.isProxy === true) {
    failedLogins++;
    if (failedLogins < 4) {
      try {
        callbackFn({
          authCredentials: {
            username: proxyUser,
            password: proxyPass
          }
        });
      } catch (e) {
        return callbackFn({
          cancel: true
        });
      }
    } else {
      return callbackFn({
        cancel: true
      });
    }

  } else {
    callbackFn();
  }
}

function parseProxy(proxy) {
  var p = proxy.split(':')
    , out = [];
  if (p.length > 7) {
    var ip = [];
    for (let i = 0; i < 8; i++) {
      ip.push(p[i].trim());
    }
    out[0] = ip.join(":");
    out[1] = p[8].trim();
    out[2] = p[9].trim();
    out[3] = p[10].trim();
    if (p.length > 11) {
      out[4] = p[11].trim();
    }

  } else {
    for (let i = 0; i < p.length; i++) {
      out[i] = p[i].trim();
    }
  }
  return out;
}

function validateProxy(proxy, port) {
  let error = "";
  if (proxy.length < 7) {
    error = "proxy " + proxy + " is invalid";
  } else if (isNaN(parseInt(port))) {
    error = "port " + port + " is invalid";
  }
  return error;
}

// 设置代理
function setProxy(proxyTxt) {
  return new Promise(resolve => {
    console.log('选择代理', proxyTxt)
    let p = parseProxy(proxyTxt);
    let proxyCurrent = p[0];
    let portCurrent = p[1];
    proxyUser = p[2];
    proxyPass = p[3];
    let error = validateProxy(proxyCurrent, portCurrent);
    if (error != "") {
      log('代理格式错误', error)
      alertMsg({ title: '代理格式错误', msg: error })
      resolve(false)
      return
    }

    let config = {
      mode: 'pac_script',
      pacScript: {
        data: `function FindProxyForURL(url, host) {
          if (host.includes("www.walmart.com")){
            return "PROXY ${proxyCurrent}:${portCurrent}";
          } else {
            return "DIRECT";
          }
        }`
      }
    };
    chrome.proxy.settings.set({
      value: config,
      scope: 'regular'
    }, function () {
      log('设置代理')
      failedLogins = 0
      setItem({ proxyConfig: true })
      setTimeout(() => {
        resolve(true)
      }, 500)
    });
  })
}
// 取消代理
function cancelProxy() {
  setItem({ proxyConfig: false })
  chrome.proxy.settings.clear({ scope: "regular" })
}

chrome.proxy.onProxyError.addListener(onProxyError);
chrome.webRequest.onAuthRequired.addListener(makeLogin, {
  urls: ["<all_urls>"]
}, ['asyncBlocking']);


/**
 * 切换代理
 */
async function switchProxy(status) {
  return new Promise(async (resolve) => {
    if (status) {
      let proxyType = await getItem('proxys-type') || '1'
      if (!(proxyList && proxyList.length > 0)) {
        console.log('无有效代理IP')
        let proxyUrl = await getItem('proxys-url') || ''
        if (proxyType == '1' && proxyUrl) {
          console.log('获取新的动态代理ip')
          // 动态代理
          let proxysConfig = await getDynamicsProxy(proxyUrl)
          console.log('获取动态代理', proxysConfig)
          if (proxysConfig) {
            proxyList = proxysConfig.split('\n').map(d => d.replace('\r', '')).filter(d => d)
          } else {
            proxyList = null
          }
          if (!(proxyList && proxyList.length > 0)) {
            console.log('动态获取ip异常，没有获取到有效ip')
            cancelProxy()
            resolve();
            return;
          }
        } else {
          alertMsg({ title: '使用代理异常', msg: '无有效代理IP' })
          cancelProxy()
          resolve();
          return;
        }
      }
      proxyIndex = Math.floor(Math.random() * proxyList.length)
      console.log('随机代理序号', proxyIndex)
      await setProxy(proxyList[proxyIndex])
      if (proxyType == '1') {
        // 动态代理,运行一次删除
        proxyList.splice(proxyIndex, 1)
      }
    } else {
      cancelProxy()
    }
    resolve()
  })
}

function group(array, subGroupLength) {
  let index = 0;
  let newArray = [];
  while (index < array.length) {
    newArray.push(array.slice(index, index += subGroupLength));
  }
  return newArray;
}

function fetchGiftCardHandle (params, size = 3) {
  return fetchGiftCard(params.cardNumber, params.pin).then(res => {
    console.log('fetchGiftCard', res)
    if (res.status == 200 && res.data && res.data.data) {
      let info =  res.data.data.giftCardBalance
      if (info != null) {
        params.cardBalance = info.cardBalance
      }
      let errors = res.data.data.errors
      if (errors && errors.length > 0) {
        // 存在错误
        params.error = errors[0].extensions.code
      }
      console.log(params)
    }
  }).catch(async e => {
    console.log(e, e.message)
    if (size > 0 && e.message == 'Request failed with status code 412') {
      console.log('风控了，需要使用代理ip')
      let flag = await getItem('proxys-flag') || false
      if (flag && isRun) {
        console.log('切换代理')
        await switchProxy(true)
        return fetchGiftCardHandle(params, --size)
      } else {
        console.log('无代理')
        params.error = '风控未配置代理：' + e.message
      }
    } else {
      params.error = e.message
    }
  })
}
// 获取动态代理
function getDynamicsProxy(url) {
  return axios.get(url).then(res => {
    if (res.status == 200) {
      return res.data
    }
    return false
  }).catch(() => false)
}

function  setTime (time = 1000 * 15) {
  return new Promise((resolve) => {
    setTimeout(() => {
        resolve()
      }, time)
  })
}

// 执行主任务
async function runData(data) {
  if (!await valid()) {
    console.log('授权文件错误')
    return
  }
  isRun = true
  setItem({ 'isRun': true })
  emit('isRun', true)
  let proxyType = await getItem('proxys-type') || '1'
  let proxyUrl = await getItem('proxys-url') || ''
  let timeout = await getItem('ptimeout') || 15
  let proxysConfig = ''
  if (proxyType == '1' && proxyUrl) {
    // 动态代理
  } else {
    // 固定ip
    proxysConfig = await getItem('proxys-config') || ''
  }
  if (proxysConfig) {
    proxyList = proxysConfig.split('\n')
  } else {
    proxyList = null
  }
  for (let i = 0; i < data.length; i++) {
     let params = data[i]
     if (!isRun) {
      params.error = '程序停止'
     continue;
    }
     let flag = await getItem('proxys-flag') || false
     if (flag) {
      await switchProxy(true)
     }
     await fetchGiftCardHandle(params)
     console.log(`${timeout}s执行下一个`)
     await setTime(timeout * 1000);
  }
  // 执行完成，导出
  exportExcel(data, '礼品卡余额数据.xlsx')
  setItem({ 'isRun': false })
  emit('isRun', false)
}

function emit(type, data) {
  chrome.runtime.sendMessage({
    type,
    data
  })
}

window.runData = runData
window.switchProxy = switchProxy

var isRun = false
setItem({ 'isRun': false })